package com.peng.leetcode.array;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

/**
 * CombinationSum
 * 39. 组合总和
 * https://leetcode.cn/problems/combination-sum/
 *
 * @author: lupeng6
 * @create: 2023/2/19 18:21
 */
public class CombinationSum {

    private List<List<Integer>> ans = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if (candidates == null || candidates.length == 0) {
            return null;
        }
        for (int i = 0; i < candidates.length; i++) {
            ArrayDeque<Integer> q = new ArrayDeque<>();
            q.offerLast(candidates[i]);
            backtrack(candidates, target, i, candidates[i], q);
        }
        return ans;
    }

    private void backtrack(int[] candidates, int target, int i, int sum, ArrayDeque<Integer> queue) {
        if (sum > target) {
            return;
        }
        if (target == sum) {
            ans.add(new ArrayList<>(queue));
            return;
        }
        for (int j = i; j < candidates.length; j++) {
            queue.offerLast(candidates[j]);
            backtrack(candidates, target, j, sum + candidates[j], queue);
            queue.pollLast();
        }
    }
}
